import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:magma/heartbeat/helpers/magma_constant.dart';
import 'package:video_player/video_player.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_tap.dart';
import '../../heartbeat/blueprint/dynamic_model.dart';
import '../../comms_link/app_state.dart';

/// Video player page view model
class VideoPlayerNavigatorViewModel extends BaseViewModel {
  late VideoPlayerController _controller;
  VideoPlayerController get controller => _controller;

  String _videoId = '';
  String get videoId => _videoId;

  bool _isPlaying = false;
  bool get isPlaying => _isPlaying;

  bool _showControls = true;
  bool get showControls => _showControls;

  /// Get dynamic details
  ContentModel? get dynamic {
    try {
      return appState.contentBroadcaster.dynamics.firstWhere(
        (d) => d.id == _videoId,
      );
    } catch (e) {
      return null;
    }
  }

  /// Initialize video player
  Future<void> initializePlayer(String videoId) async {
    _videoId = videoId;

    final videoPath = dynamic?.videoPath;
    if (videoPath == null) {
      setError('Video path not found');
      return;
    }

    try {
      setBusy(true);

      // Check if it's a local file
      if (videoPath.startsWith('http://') || videoPath.startsWith('https://')) {
        _controller = VideoPlayerController.networkUrl(Uri.parse(videoPath));
      } else {
        _controller = VideoPlayerController.file(File(videoPath));
      }

      await _controller.initialize();
      _controller.setLooping(true);

      // Listen to playback status
      _controller.addListener(() {
        if (_controller.value.isPlaying != _isPlaying) {
          _isPlaying = _controller.value.isPlaying;
          notifyListeners();
        }
      });

      // Auto play
      await _controller.play();
      _isPlaying = true;

      notifyListeners();
    } catch (e) {
      setError('Failed to load video: $e');
    } finally {
      setBusy(false);
    }
  }

  /// Toggle play/pause
  void togglePlayPause() {
    if (_controller.value.isPlaying) {
      _controller.pause();
      _isPlaying = false;
    } else {
      _controller.play();
      _isPlaying = true;
    }
    notifyListeners();
  }

  /// Toggle controls display
  void toggleControls() {
    _showControls = !_showControls;
    notifyListeners();
  }

  /// Seek forward
  void seekForward() {
    final currentPosition = _controller.value.position;
    final targetPosition = currentPosition + const Duration(seconds: 10);
    final maxDuration = _controller.value.duration;

    if (targetPosition <= maxDuration) {
      _controller.seekTo(targetPosition);
    } else {
      _controller.seekTo(maxDuration);
    }
  }

  /// Seek backward
  void seekBackward() {
    final currentPosition = _controller.value.position;
    final targetPosition = currentPosition - const Duration(seconds: 10);

    if (targetPosition >= Duration.zero) {
      _controller.seekTo(targetPosition);
    } else {
      _controller.seekTo(Duration.zero);
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

/// Video player page
class VideoPlayerStory extends StatelessWidget {
  final String videoId;

  const VideoPlayerStory({super.key, required this.videoId});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<VideoPlayerNavigatorViewModel>.reactive(
      viewModelBuilder: () => VideoPlayerNavigatorViewModel(),
      onViewModelReady: (viewModel) => viewModel.initializePlayer(videoId),
      builder: (context, viewModel, child) {
        if (viewModel.isBusy) {
          return Scaffold(
            backgroundColor: MagmaColor.black,
            body: Center(
              child: CircularProgressIndicator(color: MagmaColor.purple),
            ),
          );
        }

        if (viewModel.hasError) {
          return Scaffold(
            backgroundColor: MagmaColor.black,
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.error_outline,
                    color: MagmaColor.white,
                    size: 48.w,
                  ),
                  SizedBox(height: 16.h),
                  Text(
                    viewModel.modelError ?? 'Loading failed',
                    style: TextStyle(color: MagmaColor.white, fontSize: 16.sp),
                  ),
                  SizedBox(height: 24.h),
                  TextButton(
                    onPressed: () => QR.back(),
                    child: Text(
                      'Back',
                      style: TextStyle(
                        color: MagmaColor.purple,
                        fontSize: 16.sp,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        }

        return Scaffold(
          backgroundColor: MagmaColor.black,
          body: Stack(
            children: [
              // Video player (fill the entire screen)
              Center(
                child: AspectRatio(
                  aspectRatio: viewModel.controller.value.aspectRatio,
                  child: VideoPlayer(viewModel.controller),
                ),
              ),

              // Click area (toggle controls display)
              Positioned.fill(
                child: GestureDetector(
                  onTap: viewModel.toggleControls,
                  behavior: HitTestBehavior.opaque,
                  child: Container(color: Colors.transparent),
                ),
              ),

              // Controls
              if (viewModel.showControls) ...[
                // Top control bar (back button)
                Positioned(
                  top: 0,
                  left: 0,
                  right: 0,
                  child: Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          Colors.black.withOpacity(0.7),
                          Colors.transparent,
                        ],
                      ),
                    ),
                    child: SafeArea(
                      child: Padding(
                        padding: EdgeInsets.symmetric(
                          horizontal: 20.w,
                          vertical: 16.h,
                        ),
                        child: Row(
                          children: [
                            MagmaTap(
                              onTap: () => QR.back(),
                              child: Image.asset(
                                MagmaConstant.back,
                                width: 24.w,
                                height: 24.w,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),

                // Center playback controls
                Center(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // Rewind button
                      MagmaTap(
                        onTap: viewModel.seekBackward,
                        child: Container(
                          padding: EdgeInsets.all(12.w),
                          decoration: BoxDecoration(
                            color: Colors.black.withOpacity(0.5),
                            shape: BoxShape.circle,
                          ),
                          child: Icon(
                            Icons.replay_10,
                            color: MagmaColor.white,
                            size: 32.w,
                          ),
                        ),
                      ),

                      SizedBox(width: 40.w),

                      // Play/Pause button
                      MagmaTap(
                        onTap: viewModel.togglePlayPause,
                        child: Container(
                          padding: EdgeInsets.all(16.w),
                          decoration: BoxDecoration(
                            color: Colors.black.withOpacity(0.5),
                            shape: BoxShape.circle,
                          ),
                          child: Icon(
                            viewModel.isPlaying
                                ? Icons.pause
                                : Icons.play_arrow,
                            color: MagmaColor.white,
                            size: 40.w,
                          ),
                        ),
                      ),

                      SizedBox(width: 40.w),

                      // Fast forward button
                      MagmaTap(
                        onTap: viewModel.seekForward,
                        child: Container(
                          padding: EdgeInsets.all(12.w),
                          decoration: BoxDecoration(
                            color: Colors.black.withOpacity(0.5),
                            shape: BoxShape.circle,
                          ),
                          child: Icon(
                            Icons.forward_10,
                            color: MagmaColor.white,
                            size: 32.w,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),

                // Bottom progress bar
                Positioned(
                  bottom: 0,
                  left: 0,
                  right: 0,
                  child: Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.bottomCenter,
                        end: Alignment.topCenter,
                        colors: [
                          Colors.black.withOpacity(0.7),
                          Colors.transparent,
                        ],
                      ),
                    ),
                    child: SafeArea(
                      child: Padding(
                        padding: EdgeInsets.symmetric(
                          horizontal: 20.w,
                          vertical: 16.h,
                        ),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            // Progress indicator
                            VideoProgressIndicator(
                              viewModel.controller,
                              allowScrubbing: true,
                              colors: VideoProgressColors(
                                playedColor: MagmaColor.purple,
                                bufferedColor: MagmaColor.white.withOpacity(
                                  0.3,
                                ),
                                backgroundColor: MagmaColor.white.withOpacity(
                                  0.1,
                                ),
                              ),
                            ),

                            SizedBox(height: 8.h),

                            // Time display
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  _formatDuration(
                                    viewModel.controller.value.position,
                                  ),
                                  style: TextStyle(
                                    color: MagmaColor.white,
                                    fontSize: 12.sp,
                                  ),
                                ),
                                Text(
                                  _formatDuration(
                                    viewModel.controller.value.duration,
                                  ),
                                  style: TextStyle(
                                    color: MagmaColor.white,
                                    fontSize: 12.sp,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ],
          ),
        );
      },
    );
  }

  /// Format duration
  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final hours = twoDigits(duration.inHours);
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));

    if (duration.inHours > 0) {
      return '$hours:$minutes:$seconds';
    } else {
      return '$minutes:$seconds';
    }
  }
}
